import React, { useState, useRef, useEffect } from 'react';
import { sendTextForSpeech, mockTextToSpeech, sendMessageToOllama } from '../api/llmService';
import styles from '../styles/Home.module.css';
import { HistoryItem } from './HistoryRecord';

interface TextInputProps {
  useMockApi?: boolean;
  selectedHistory?: HistoryItem | null;
}

const TextInput: React.FC<TextInputProps> = ({ 
  useMockApi = true, // 默认使用模拟API，实际开发中改为false
  selectedHistory = null
}) => {
  const [text, setText] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);
  const [audioUrl, setAudioUrl] = useState<string | null>(null);
  const [modelResponse, setModelResponse] = useState<string>('');
  const audioRef = useRef<HTMLAudioElement>(null);

  // 处理选中的历史记录
  useEffect(() => {
    if (selectedHistory && selectedHistory.type === 'text') {
      setText(selectedHistory.userInput);
      if (selectedHistory.modelResponse) {
        setModelResponse(selectedHistory.modelResponse);
      }
    }
  }, [selectedHistory]);

  // 处理文本输入变化
  const handleTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setText(e.target.value);
  };

  // 保存历史记录
  const saveToHistory = (userInput: string, modelResponse: string, audioUrl: string | null = null) => {
    try {
      // 获取现有历史记录
      const savedHistory = localStorage.getItem('llm-voice-history');
      let historyItems: HistoryItem[] = [];
      
      if (savedHistory) {
        historyItems = JSON.parse(savedHistory);
      }
      
      // 创建新的历史记录项
      const newHistoryItem: HistoryItem = {
        id: `text-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
        timestamp: Date.now(),
        type: 'text',
        userInput,
        modelResponse,
        audioUrl: audioUrl || undefined
      };
      
      // 添加到历史记录
      historyItems.push(newHistoryItem);
      
      // 如果历史记录太长，删除最旧的
      if (historyItems.length > 50) {
        historyItems = historyItems.slice(-50);
      }
      
      // 保存到localStorage
      localStorage.setItem('llm-voice-history', JSON.stringify(historyItems));
    } catch (error) {
      console.error('保存历史记录失败:', error);
    }
  };

  // 发送文本到大模型并获取音频
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!text.trim() || isProcessing) return;
    
    setIsProcessing(true);
    setAudioUrl(null);
    
    try {
      // 1. 发送文本到大模型获取回复
      const response = useMockApi 
        ? `这是来自大模型的模拟回复：${text}` 
        : await sendMessageToOllama(text);
      
      setModelResponse(response);
      
      // 2. 将大模型回复转换为语音
      let finalAudioUrl = null;
      
      if (useMockApi) {
        // 模拟延迟
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 使用浏览器内置的语音合成API
        if ('speechSynthesis' in window) {
          const utterance = new SpeechSynthesisUtterance(response);
          utterance.lang = 'zh-CN';
          speechSynthesis.speak(utterance);
          
          // 设置一个模拟的音频URL
          finalAudioUrl = '模拟音频 - 已使用浏览器语音合成API播放';
          setAudioUrl(finalAudioUrl);
        } else {
          // 如果浏览器不支持语音合成，使用模拟API
          const audioUrlResult = await mockTextToSpeech(response);
          finalAudioUrl = audioUrlResult;
          setAudioUrl(audioUrlResult);
        }
      } else {
        // 使用真实API
        const audioUrlResult = await sendTextForSpeech(response);
        finalAudioUrl = audioUrlResult;
        setAudioUrl(audioUrlResult);
        
        // 3. 自动播放音频
        if (audioRef.current) {
          audioRef.current.load();
          try {
            await audioRef.current.play();
          } catch (playError) {
            console.error('自动播放失败，可能需要用户交互:', playError);
          }
        }
      }
      
      // 保存到历史记录
      saveToHistory(text, response, finalAudioUrl);
      
    } catch (error) {
      console.error('处理失败:', error);
      alert('处理请求失败，请重试。');
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <div className={styles.textInputSection}>
      <h2 className={styles.sectionTitle}>文本输入</h2>
      
      <form onSubmit={handleSubmit}>
        <div className={styles.textInputContainer}>
          <textarea
            className={`input ${styles.textInput}`}
            value={text}
            onChange={handleTextChange}
            placeholder="请输入要发送给大模型的文字..."
            rows={4}
            disabled={isProcessing}
          />
        </div>
        
        <button 
          type="submit" 
          className="btn btn-primary"
          disabled={!text.trim() || isProcessing}
        >
          {isProcessing ? '处理中...' : '发送'}
        </button>
      </form>
      
      {modelResponse && (
        <div className={`${styles.resultContainer} mt-4`}>
          <h3 className="mb-4">大模型回复:</h3>
          <p>{modelResponse}</p>
        </div>
      )}
      
      {audioUrl && (
        <div className={styles.audioPlayer}>
          <h3 className="mb-4">语音回复:</h3>
          {audioUrl.startsWith('模拟音频') ? (
            <p>{audioUrl}</p>
          ) : (
            <audio ref={audioRef} controls>
              <source src={audioUrl} type="audio/mpeg" />
              您的浏览器不支持音频播放。
            </audio>
          )}
        </div>
      )}
    </div>
  );
};

export default TextInput; 